import 'dart:io';
import 'package:flutter/material.dart';

import 'package:image_picker/image_picker.dart';
import 'package:modal_progress_hud/modal_progress_hud.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import '../GetNowDateAndFormat.dart';
import '../toast/BotToastCall.dart';
import '../../package/photo/PageViewPart.dart';
import '../../package/package_model_comm.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/cupertino.dart';
import '../loading/LogdingContent.dart';

/*
 * @class TakePhotos
 * @author: ZhongWb
 * @date: 2019/12/12 15:55
 * @description 拍照、相册
 *
 * ModalProgressHUD:^0.1.3 加载菊花插件 依赖不能低于0.1
 * flutter_image_compress:^0.6.3 图片压缩 依赖
 * multi_image_picker:^4.6.0 多图片选择插件 依赖不能低于3.0
 * path_provider:^1.5.1  文件路径插件 依赖
 * !!!重要-必须配置！安卓-ios配置多图片选择 参照multi_image_picker手册 如下
 * https://sh1d0w.github.io/multi_image_picker/#/initialsetup
 **/
class TakePhotos extends StatefulWidget {
  List<PhotoModel>  urlImgInfo;//图片数据
  int maxCountImg;//图片张数
  ValueChanged<List<File>> valueChanged;//图片回调
  ValueChanged<List<PhotoModel>>  delurlImgInfo;//删除后的图片数据
  double widght;
  double height;
  int line;//单行个数
  String baseUrl;// 图片基础地址
  double icon_right;//删除按钮位置top
  double icon_top;//删除按钮位置right
  int imageQuality;//图片质量 范围0 - 100  数值越低 质量越小 内存越小，相反越大
  //图片封装加个开关  区分权限的问题，
  bool isOnTap; // true 可点击拍照按钮  false不可点击拍照按钮  默认值为true
  //删除按钮切换开关，
  bool isShowPaddingMagin;  //true 显示外面，false显示外面  默认值为true

  TakePhotos({
    this.baseUrl,
    this.imageQuality:25,
    this.line:5,
    this.valueChanged,
    this.urlImgInfo,
    this.maxCountImg:5,
    this.height:65,
    this.widght,
    this.delurlImgInfo,
    this.isOnTap:true,
    this.isShowPaddingMagin:true,
    this.icon_right,
    this.icon_top,
  });
  @override
  _TakePhotosState createState() => _TakePhotosState();
}

class _TakePhotosState extends State<TakePhotos> {
  //拍的照片
  File _image;
  //图片多选返回的资源
  List<Asset> images = List<Asset>();
  //图片多选返回的异常
  String _error;
  //图片组件
  List<Widget> listWid = [];
  //控制菊花
  bool _loading = false;

  //弹出框字体样式
  TextStyle textStyle = new TextStyle(
    color: Color(0xff333333),
    fontSize: 16,
  );

  //初始化
  @override
  void initState() {
    super.initState();
    print("初始化只进来一次");
    initUpdate();
  }

  //更新
  @override
  void didUpdateWidget(TakePhotos oldWidget) {
    super.didUpdateWidget(oldWidget);
    print("执行了setState会进来");
    initUpdate();
  }

  //初始化视图 、 更新视图
  initUpdate(){
    //清除组件并重新赋值
    listWid.clear();
    //判断是否有照片 有 则添加图片widget 没有则添加一个拍照按钮
    if(widget.urlImgInfo!=null && widget.urlImgInfo.length!=0){
      for(int i=0;i<widget.urlImgInfo.length;i++){
        listWid.add(
          InkWell(
            child: Stack(
              overflow: Overflow.visible,
              children: <Widget>[
                Container(
                  width: 60,
                  height: 60,
                  //File不为空 显示本地图片 否则 显示网络图片
                  child: widget.urlImgInfo[i].file!=null?Image.file(widget.urlImgInfo[i].file,fit: BoxFit.cover,):FadeInImage.assetNetwork(placeholder: "images/package/lietu.png", image: "${widget.baseUrl+widget.urlImgInfo[i].url}",fit: BoxFit.cover,),
                ),
                  widget.isShowPaddingMagin == true?
                  Positioned(
                    top:  widget.icon_top ?? -0.1,
                    right:  widget.icon_right ?? -0.1,
                    child: InkWell(
                      //圆的删除X
//                      child: ClipOval(child: Container(
//                        width: 20,
//                        height: 20,
//                        alignment: Alignment.center,
//                        child: Text("X",style: TextStyle(color: Colors.white),),
//                        color: Colors.red,
//                      ),),
                    //方的删除X
                      child: Container(
                        width: 15,
                        height: 15,
                        alignment: Alignment.center,
//                        child: Text("×",style: TextStyle(color: Colors.white,fontSize: 15),),
                        child: Image.asset("images/icon_close.png",),
                        // color: widget.icon_close ?? Colors.red,
                      ),
                      onTap: (){
                        //删除按钮的点击
                        if(!widget.isOnTap){
                          return;
                        }
                        print("删除");
                        setState(() {
                          widget.urlImgInfo.remove(widget.urlImgInfo[i]);
                        });
                        widget.delurlImgInfo(widget.urlImgInfo);
//                        widget.delurlImgInfo = widget.urlImgInfo;
                      },
                    ),
                  ):Container(),
              ],
            ),
            onTap: (){
              print("点击了查看大图:"+widget.urlImgInfo.toString());
              Navigator.push(context, MaterialPageRoute(builder: (context)=>Pageview(widget.urlImgInfo,i,widget.baseUrl,widget.isShowPaddingMagin,widget.isOnTap))).then((returnImageList){
                print("查看大图返回："+returnImageList.toString());
                //更新图片组件
                setState(() {
                  widget.urlImgInfo = returnImageList;
                });
              });
            },
          ),
        );
      }
      //图片长度  小于最大图片才添加
      if(listWid.length < widget.maxCountImg){
        listWid.add(photoButton(),);
      }
    }else{
      //图片长度  小于最大图片才添加
      if(listWid.length < widget.maxCountImg){
        listWid.add(photoButton(),);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      //width: widget.widght,
      //height: widget.height,
      alignment: Alignment.centerLeft,
      child: GridView.builder(
          physics: const NeverScrollableScrollPhysics(),//禁止视图滑动
          shrinkWrap: true,
          padding: EdgeInsets.only(top: 5,right: 7),
          itemCount: listWid.length,
          //SliverGridDelegateWithFixedCrossAxisCount 构建一个横轴固定数量Widget
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            //横轴元素个数
            crossAxisCount: widget.line,
            //纵轴间距
            mainAxisSpacing: 10.0,
            //横轴间距
            crossAxisSpacing: 10.0,
          ),
          itemBuilder: (BuildContext context, int index) {
            //Widget Function(BuildContext context, int index)
            return listWid[index];
          }),
    );

  }

  //  拍照
  Future getImage(state) async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: widget.imageQuality);
    _image = image;
    if (_image==null) return;
    print(getPrintSize(_image.lengthSync()));
    widget.valueChanged([_image]);
  }

  //  相册
  Future loadAssets(state) async {
    images = List<Asset>();
    //选择图片后返回的集合
    List<Asset> resultList = [];
    //转换后的图片文件集合
    List<File> fileList = [];
    String error;
    int max = (widget.maxCountImg-listWid.length)+1;
    try {
      resultList = await MultiImagePicker.pickImages(
        maxImages: max,
        materialOptions: MaterialOptions(
        actionBarTitle: "选择照片",//主标题
        allViewTitle: "选择照片",//子标题
        actionBarColor: "#1E90FF",//标题栏颜色
        actionBarTitleColor: "#ffffff",//标题字体颜色
        lightStatusBar: true,//系统状态栏
        statusBarColor: '#1E90FF',//状态栏颜色
        startInAllView: false,//false树样式  ， true 显示全部
        selectCircleStrokeColor: "#1E90FF",//勾选后的圈圈颜色
        selectionLimitReachedText: "已达到最大可选张数",
      ),
      );
    } on Exception catch (e) {
      error = e.toString();
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;
    //将选择的图片赋值给图片集合
    images = resultList;
    if (error == null) _error = 'No Error Dectected';
    //选择的照片为空时 停止以下行为
    if (images.length==0)  return;
    //启动转圈圈
    state((){
      _loading = true;
    });
    //转换每个图片为File
    for(int i=0;i<images.length;i++){
      print("第${i+1}张图片");
      //getByteData 图片压缩，quality 图片质量 返回的是字节
      await images[i].getByteData(quality: 100).then((v){
        //从字节缓冲区得到图片字节流
        List<int> imageData = v.buffer.asUint8List();
        //打印压缩前大小
        print("压缩前大小：${getPrintSize((imageData.length/75)+imageData.length)}");
        //限制图片选择大小
        if((imageData.length/75)+imageData.length>5242880){
          state((){
            _loading = false;
          });
          BotToastCall.ShowMessage("第${i+1}张图片为${getPrintSize((imageData.length/75)+imageData.length)} 超过5MB,请重新选择",textStyle: TextStyle(fontSize: 16,color: Colors.white),align:Alignment.center,seconds: 3);
          return;
        }
        //打印压缩后大小
        print("压缩后大小："+getPrintSize(imageData.length));
        //调用图片类型转换方法
        writeToFile(imageData).then((fileValue){
          //将转换后的图片文件插入到 list集合
          fileList.add(fileValue);
          // 已压缩完 停止转圈圈 并回调图片，选择的图片长度 等于 转换后的 长度
          if(images.length == fileList.length){
            print("图片全部压缩完成");
            state((){
              _loading = false;
            });
            //回调图片
            widget.valueChanged(fileList);
          }
        });
      });
    }
  }

  //打印内存 保留两位小数
  getPrintSize( limit){
    String  size = "";
    //内存转换
    if(limit < 0.1 * 1000){                            //小于0.1KB，则转化成B
      size = limit.toString().substring(0,size.indexOf(".")+3) + "  B";
    }else if(limit < 0.1 * 1000 * 1000){            //小于0.1MB，则转化成KB
      size = (limit/1024).toString().substring(0,size.indexOf(".")+3) + "  KB";
    }else if(limit < 0.1 * 1000 * 1000 * 1000){        //小于0.1GB，则转化成MB
      size = (limit/(1000 * 1000)).toString() ;
      print(size.indexOf("."));
      size = size.substring(0,size.indexOf(".")+3) + "  MB";
    }else{                                            //其他转化成GB
      size = (limit/(1000 * 1000 * 1000)).toString();
      size = size.substring(0,size.indexOf(".")+3) + "  GB";
    }
    return size;
  }

  //将压缩后的图片字节写入File
  Future<File> writeToFile(List<int> imageByte) async{
    //    getExternalStorageDirectory是app根目录   压缩才有临时目录
    final Directory _directory = await getTemporaryDirectory();
    //如果路径不存在  则创建
    final Directory _imageDirectory = await new Directory('${_directory.path}/image/').create(recursive: true);
    File file = File('${_imageDirectory.path}${GetNowDateAndFormatFileName()}.jpg');//文件
    if (imageByte!=null && imageByte.length!=0) {
      file.writeAsBytesSync(imageByte, flush: true, mode: FileMode.write);
      debugPrint("图片写入完成："+file.toString());
      return file;
    }
  }

  //拍照按钮
  Widget photoButton(){
    return InkWell(
      onTap: (){
        //拦截拍照按钮的点击
        if(!widget.isOnTap){
          return;
        }
        showDialog(context: context,builder: (ctx){
          return Material(
            color: Colors.transparent,
            child: StatefulBuilder(
              builder: (context,state){
                return ModalProgressHUD(
                  //引用自定义样式
                  progressIndicator: LogdingContent(fg: 0,text: "操作中"),
                  inAsyncCall: _loading,
                  child: Stack(
                    children: <Widget>[
                      InkWell(
                        child: Container(
                          width: MediaQuery.of(context).size.width,
                          height: MediaQuery.of(context).size.height,
                          color: Colors.transparent,
                        ),
                        onTap: (){
                          Navigator.pop(context);
                        },
                      ),
                      Positioned(
                        bottom: 0,
                        child: Container(
                          width: MediaQuery.of(context).size.width,
                          padding: EdgeInsets.only(top: 6.0),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.only(
                              topLeft: Radius.circular(6.0),
                              topRight: Radius.circular(6.0),
                            ),
                          ),
                          height: 167.0,
                          child: Column(
                            children: <Widget>[
                              InkWell(
                                onTap:(){
                                  getImage(state);
                                },
                                child: Container(
                                  height: 50,
                                  color: Colors.white,
                                  alignment: Alignment.center,
                                  child: Text(
                                    "拍照",
                                    style: textStyle,
                                  ),
                                ),
                              ),
                              Container(
                                height: 1,
                                color: Color(0xfff5f5f5),
                              ),
                              InkWell(
                                onTap: (){
                                  loadAssets(state);
                                },
                                child: Container(
                                  height: 50,
                                  color: Colors.white,
                                  alignment: Alignment.center,
                                  child: Text(
                                    "从相册选择",
                                    style: textStyle,
                                  ),
                                ),
                              ),
                              Container(
                                height: 10,
                                color: Color(0xfff5f5f5),
                              ),
                              InkWell(
                                onTap: () {
                                  Navigator.pop(context);
                                },
                                child: Container(
                                  height: 50,
                                  color: Colors.white,
                                  alignment: Alignment.center,
                                  child: Text(
                                    "取消",
                                    style: textStyle,
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),);
              },
            ),
          );
        });
      },
      child: Image.asset("images/package/PhotoButton.png"),
    );
  }
}
